<template>
  <div class="w-full h-full flex flex-col items-center">
    <h1 class="text-2xl font-bold my-8">卡牌游戏</h1>
    <button
      @click="showAllCards"
      v-if="!isGameStarted && !showingAllCards && !isShuffled"
      class="bg-blue-500 text-white px-4 py-2 rounded mb-4"
    >
      开始游戏
    </button>
    <button
      @click="shuffleAndShow"
      v-if="showingAllCards && !isGameStarted && !isShuffled"
      class="bg-blue-500 text-white px-4 py-2 rounded mb-4"
    >
      洗牌
    </button>
    <button
      @click="startGame"
      v-if="isShuffled && !isGameStarted"
      class="bg-blue-500 text-white px-4 py-2 rounded mb-4"
    >
      发牌
    </button>
    <button
      v-if="isGameStarted && !isCardsRevealed && isDealing"
      class="bg-blue-500 text-white px-4 py-2 rounded mb-4"
    >
      发牌中...
    </button>
    <button
      @click="revealCards"
      v-if="isGameStarted && !isCardsRevealed && !isDealing"
      class="reveal-button bg-green-500 text-white px-4 py-2 rounded mt-4"
    >
      开牌
    </button>
    <div
      v-if="isCardsRevealed && winner !== null"
      class="winner mt-4 bg-yellow-300 text-black px-6 py-2 rounded font-bold"
    >
      获胜玩家: 玩家 {{ winner + 1 }} 🎉
    </div>
    <div
      v-if="!showingAllCards"
      class="grid grid-cols-4 gap-4 w-full h-full items-start mt-4"
    >
      <div
        v-for="(player, index) in players"
        :key="index"
        :class="['p-4', 'relative']"
      >
        <h2 class="text-lg font-semibold mb-2 text-center">
          玩家 {{ index + 1 }}
        </h2>
        <transition-group
          name="deal"
          tag="ul"
          class="flex flex-col items-center"
        >
          <li
            v-for="(card, cardIndex) in player.cards"
            :key="card"
            class="card relative w-10 h-16 border rounded-sm bg-white shadow-md flex items-center justify-center"
            :style="{ top: `${cardIndex * -30}px` }"
          >
            <span
              v-if="isCardsRevealed"
              :class="['absolute top-1 left-1 text-sm', cardColor(card)]"
            >
              {{ cardSymbol(card) }}
            </span>
            <span
              v-else
              class="w-full h-full flex items-center justify-center bg-gray-200 bg-[repeating-linear-gradient(45deg,#cccccc_0_10px,#e0e0e0_10px_20px)] rounded"
            ></span>
          </li>
        </transition-group>
      </div>
    </div>
    <div
      v-if="showingAllCards && !isGameStarted"
      class="flex flex-col gap-2 mt-4"
    >
      <div class="flex justify-center" v-for="rowIndex in 4" :key="rowIndex">
        <div
          v-for="(card, index) in cards.slice(
            (rowIndex - 1) * 13,
            rowIndex * 13
          )"
          :key="index"
          class="w-10 h-16 border rounded-sm shadow-md flex items-center justify-center relative"
          :class="
            isShuffled
              ? 'bg-[repeating-linear-gradient(45deg,#cccccc_0_10px,#e0e0e0_10px_20px)]'
              : 'bg-white'
          "
          :style="{
            marginLeft: `${index !== 0 ? -20 : 0}px`,
            zIndex: `${index}`,
          }"
        >
          <span
            v-if="showingAllCards && !isShuffled"
            :class="['absolute top-1 left-1 text-sm', cardColor(card)]"
          >
            {{ cardSymbol(card) }}
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from "vue";

export default {
  name: "CardGame",
  setup() {
    const cards = ref([
      "2@",
      "2^",
      "2#",
      "2*",
      "3@",
      "3^",
      "3#",
      "3*",
      "4@",
      "4^",
      "4#",
      "4*",
      "5@",
      "5^",
      "5#",
      "5*",
      "6@",
      "6^",
      "6#",
      "6*",
      "7@",
      "7^",
      "7#",
      "7*",
      "8@",
      "8^",
      "8#",
      "8*",
      "9@",
      "9^",
      "9#",
      "9*",
      "10@",
      "10^",
      "10#",
      "10*",
      "J@",
      "J^",
      "J#",
      "J*",
      "Q@",
      "Q^",
      "Q#",
      "Q*",
      "K@",
      "K^",
      "K#",
      "K*",
      "A@",
      "A^",
      "A#",
      "A*",
    ]);
    const players = ref([]);
    const winner = ref(null);
    const isGameStarted = ref(false);
    const isCardsRevealed = ref(false);
    const isDealing = ref(false);
    const showingAllCards = ref(false);
    const isShuffled = ref(false);

    const shuffleCards = () => {
      for (let i = cards.value.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [cards.value[i], cards.value[j]] = [cards.value[j], cards.value[i]];
      }
    };

    const dealCards = () => {
      players.value = [
        { cards: [] },
        { cards: [] },
        { cards: [] },
        { cards: [] },
      ];
      let cardIndex = 0;
      isDealing.value = true;
      const interval = setInterval(() => {
        if (cardIndex >= cards.value.length) {
          clearInterval(interval);
          isDealing.value = false;
          return;
        }
        const playerIndex = cardIndex % 4;
        players.value[playerIndex].cards.push(cards.value[cardIndex]);
        cardIndex++;
      }, 100);
    };

    const findWinner = () => {
      let maxScore = -1;
      let winningPlayer = -1;
      players.value.forEach((player, index) => {
        const cardGroups = {};
        player.cards.forEach((card) => {
          const cardValue = card.slice(0, -1);
          cardGroups[cardValue] = (cardGroups[cardValue] || 0) + 1;
        });
        const maxGroupSize = Math.max(...Object.values(cardGroups));
        if (maxGroupSize > maxScore) {
          maxScore = maxGroupSize;
          winningPlayer = index;
        }
      });
      winner.value = winningPlayer;
    };

    const startGame = () => {
      isGameStarted.value = true;
      isCardsRevealed.value = false;
      showingAllCards.value = false;
      winner.value = null;
      dealCards();
    };

    const showAllCards = () => {
      showingAllCards.value = true;
    };

    const shuffleAndShow = () => {
      shuffleCards();
      showingAllCards.value = true;
      setTimeout(() => {
        isShuffled.value = true;
      }, 1000);
    };

    const revealCards = () => {
      findWinner();
      isCardsRevealed.value = true;
    };

    const cardSymbol = (card) => {
      const symbolMap = {
        "@": "♠",
        "^": "♥",
        "#": "♦",
        "*": "♣",
      };
      return card.slice(0, -1) + symbolMap[card.slice(-1)];
    };

    const cardColor = (card) => {
      const colorMap = {
        "@": "text-black",
        "^": "text-red-500",
        "#": "text-red-500",
        "*": "text-black",
      };
      return colorMap[card.slice(-1)];
    };

    return {
      cards,
      players,
      winner,
      isGameStarted,
      isCardsRevealed,
      isDealing,
      showingAllCards,
      isShuffled,
      startGame,
      revealCards,
      shuffleAndShow,
      showAllCards,
      cardSymbol,
      cardColor,
    };
  },
};
</script>
